﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace QRCodeNet
{
	public class Config
	{
		public static Config config = new Config();
		string fileName = "config.xml";
		public Config()
		{
			if (!Load())
			{
				No = Color = Std = FootSize = ProName = Material = EAN13 = Level = "";
			}
		}
		public Config(Config old)
		{
			var p = old.GetType().GetProperties();
			foreach (var item in p)
			{
				var oldVal = item.GetValue(old);
				this.GetType().GetProperty(item.Name).SetValue(this, oldVal);
			}
		}
		public bool Save()
		{
			XmlDocument doc = new XmlDocument();
			XmlNode root = doc.CreateElement("root");
			doc.AppendChild(root);

			var p = GetType().GetProperties();
			foreach (var item in p)
			{
				XmlElement n = doc.CreateElement(item.Name);
				n.SetAttribute("value", item.GetValue(this).ToString());
				root.AppendChild(n);
			}
			try
			{
				doc.Save(fileName);
			}
			catch (Exception e)
			{
				ExceptionDealer.ShowException(e);
				return false;
			}
			return true;
		}
		public bool Load()
		{
			try
			{
				XmlDocument doc = new XmlDocument();
				doc.Load(fileName);
				var p = GetType().GetProperties();
				XmlNode root = doc.FirstChild;
				foreach (var item in p)
				{
					var t = root[item.Name];
					if (item.PropertyType == typeof(string))
						item.SetValue(this, t.GetAttribute("value"));
					else if (item.PropertyType == typeof(int))
						item.SetValue(this, Convert.ToInt32(t.GetAttribute("value")));
				}
			}
			catch (Exception e)
			{
				ExceptionDealer.ShowException(e);
				return false;
			}
			return true;
		}
		public int EachRow { get; set; }
		public int EachCol { get; set; }
		public int QRWid { get; set; }
		public int QRHei { get; set; }
		public int XOffset { get; set; }
		public int YOffset { get; set; }
		public int BrdWid { get; set; }
		public int BrdHei { get; set; }
		public string No { get; set; }
		public string Color { get; set; }
		public string Std { get; set; }
		public string FootSize { get; set; }
		public string ProName { get; set; }
		public string Material { get; set; }
		public string Level { get; set; }
		public int NoInit { get; set; }
		public int BarInit { get; set; }
		public string EAN13 { get; set; }
		public int EachBox { get; set; }
		public int Count { get; set; }
		public int HistoryNum { get; set; }

	}
}
